package 知识点复习.异步回调.handle统一处理异常;

import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;

public class CompletableDemo2 {
    public static void handleDemo() throws Exception {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                //模拟执行1秒
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + ":抛出异常");
            throw new RuntimeException(Thread.currentThread().getName() + ":发生异常");
        });

        //统一处理异常和结果
        future.handle(new BiFunction<Void, Throwable, Void>() {
            @Override
            public Void apply(Void unused, Throwable throwable) {
                if (throwable == null) {
                    System.out.println(Thread.currentThread().getName() + ":没有发生异常!");
                } else {
                    System.out.println(Thread.currentThread().getName() + ":sorry,发生了异常!");
                }
                return null;
            }
        });
        future.get();
    }

    public static void main(String[] args) throws Exception {
        handleDemo();
    }
}
